package com.erlang4j.internal.basicIo;

import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangPid;

public class MockBasicMailBox implements IBasicMailBox {

	public int receiveCount;
	public OtpErlangObject[] receive;
	private int index;
	public long timeout;
	public OtpErlangPid self;
	public Object serverName;
	public OtpErlangObject sentObject;
	private int sendCount;

	public MockBasicMailBox(OtpErlangPid self, OtpErlangObject... receive) {
		super();
		this.receive = receive;
		this.self = self;
	}

	@Override
	public OtpErlangObject receive(long timeout) {
		this.timeout = timeout;
		return nextReceive(timeout);
	}

	@Override
	public OtpErlangObject receive() {
		return nextReceive(1000000000);
	}

	private OtpErlangObject nextReceive(long timeout) {
		receiveCount++;
		if (index < receive.length)
			return receive[index++];
		try {
			Thread.sleep(timeout);
			return null;
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public OtpErlangPid self() {
		return self;
	}

	@Override
	public void send(Object serverNameOrPid, OtpErlangObject object) {
		this.serverName = serverNameOrPid;
		this.sentObject = object;
		sendCount++;
	}

}
